#pragma once
#include <aaudio/AAudio.h>
#include <android/log.h>

#include <thread>

#include "include/aduio_buffer.h"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
}
namespace codec {
class AudioCodec {
 public:
  bool init(AVCodecParameters* codec_params);
  void close();
  bool initAAudio();
  bool sendPacket(AVPacket* packet);
  void swrController(AVFrame* frame);
  void setTarget(double video_s);
  void flush() {
    if (codec_ctx_) {
      avcodec_flush_buffers(codec_ctx_);
    }
  }
  int64_t getAudioPosition();
  AVFrame* receiveFrame();
  int getSampleRate() { return AAudioStream_getSampleRate(stream); }
  // 在AudioCodec中新增
  int64_t getTimeBase() const {
    return 1000000;  // 1秒=10^6微秒 (AV_TIME_BASE)
  }
  void stop() {
    __android_log_print(ANDROID_LOG_INFO, "FHQ", "stop");
    aaudio_result_t result = AAudioStream_requestStop(stream);  // 停止播放
    aaudio_stream_state_t targetState = AAUDIO_STREAM_STATE_STOPPED;
    AAudioStream_waitForStateChange(stream, AAUDIO_STREAM_STATE_STOPPED,
                                    &targetState, 100e6);
    if (result != AAUDIO_OK) {
      __android_log_print(ANDROID_LOG_INFO, "FHQ", "STOPPED failed: %s",
                          AAudio_convertResultToText(result));
    }
  }
  void requestFlush() {
    pcm_buffer.clear();
    AAudioStream_requestFlush(stream);  // 清空内部缓冲区
    aaudio_stream_state_t targetState1 = AAUDIO_STREAM_STATE_FLUSHED;
    AAudioStream_waitForStateChange(stream, AAUDIO_STREAM_STATE_FLUSHED,
                                    &targetState1, 100e6);
  }

  void restart() {
    aaudio_result_t result = AAudioStream_requestStart(stream);
    aaudio_stream_state_t targetState = AAUDIO_STREAM_STATE_STARTED;
    AAudioStream_waitForStateChange(stream, AAUDIO_STREAM_STATE_STARTED,
                                    &targetState, 200e6);
  }

  void pause() {
    if (AAudioStream_getState(stream) == AAUDIO_STREAM_STATE_STARTED) {
      aaudio_result_t result = AAudioStream_requestPause(stream);
      aaudio_stream_state_t targetState = AAUDIO_STREAM_STATE_PAUSED;
      AAudioStream_waitForStateChange(stream, AAUDIO_STREAM_STATE_PAUSING,
                                      &targetState, 200e6);
      if (result != AAUDIO_OK) {
        __android_log_print(ANDROID_LOG_INFO, "FHQ", "Pause failed: %s",
                            AAudio_convertResultToText(result));
      }
    }
  }

  void resume() {
    int64_t framesWritten = AAudioStream_getFramesWritten(stream);
    int64_t framesRead = AAudioStream_getFramesRead(stream);
    int32_t bufferSize = AAudioStream_getBufferSizeInFrames(stream);

    // 计算未播放帧数
    int32_t pendingFrames = framesWritten - framesRead;
    bool isBufferEmpty = (pendingFrames <= 0);

    __android_log_print(ANDROID_LOG_INFO, "FHQ", " pendingFrames%d",
                        pendingFrames);
    if (AAudioStream_getState(stream) == AAUDIO_STREAM_STATE_PAUSED) {
      // 预热缓冲区防止恢复爆音
      AAudioStream_setBufferSizeInFrames(
          stream, AAudioStream_getFramesPerBurst(stream) * 2);

      aaudio_result_t result = AAudioStream_requestStart(stream);
      aaudio_stream_state_t targetState = AAUDIO_STREAM_STATE_STARTED;
      AAudioStream_waitForStateChange(stream, AAUDIO_STREAM_STATE_PAUSING,
                                      &targetState, 200e6);
      if (result != AAUDIO_OK) {
        __android_log_print(ANDROID_LOG_INFO, "FHQ", "Pause failed: %s",
                            AAudio_convertResultToText(result));
      } else {
        __android_log_print(ANDROID_LOG_INFO, "FHQ", "Pause success:");
      }
    }
  }

 private:
  int out_channels_;
  int64_t mSeekStartFramePos = 0;
  int64_t mBaseFrameOffset;
  AudioBuffer pcm_buffer = AudioBuffer(48000 * 2);  // 48kHz * 立体声
  AVCodecContext* codec_ctx_ = nullptr;
  const AVCodec* codec_ = nullptr;
  SwrContext* swrCtx_ = nullptr;
  AAudioStream* stream = nullptr;
  static aaudio_data_callback_result_t audioCallback(AAudioStream* stream,
                                                     void* userData,
                                                     void* audioData,
                                                     int32_t numFrames);
};
}  // namespace codec